/* eslint-disable */

import React, { useState, Fragment, useEffect, } from 'react';
import { connect } from 'dva';
import { Table, Card, Button, Popconfirm, message, ConfigProvider } from 'antd';
import TablePagination from '../../components/common/TablePagination';
import TreePagination from '../../components/common/TreePagination';
import styles from './index.less';
import Search from './search';
import AddInterview from './addInterview';
import { deleteVisitInformation, getAllDictionaryValueNotPage, } from '../../services/interview/intervierServer';
import { downloadExcel } from '../../services/home/homeService';
import img from '../../assets/logo-loading.gif';
import style from '../index.css';
import { emptyText } from '../../utils/commonUtil';


const Index = props => {
  const [showAdd, setShowAdd] = useState(false);
  const [detailData, setDetailData] = useState(null);
  const [fileType, setFileType] = useState([]);
  const [selectIndex, setSelectIndex] = useState('');
  const [isEdit, setIsEdit] = useState(false);
  const [editId, setEditId] = useState('');
  const [editStatus, setEditStatus] = useState(null);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [list, setList] = useState([])
  const { interviewReportModel, dispatch, globalModel, } = props;
  const { dataSource, loading, total, currentPage, pageSize, searchData, personalizedColumn, allData, treeColumns, approvalList, menuData, orgChooseList } = interviewReportModel;
  const { query } = globalModel

  const menuProcessing = (value) => {
    let count = menuData.filter(item => item.indexOf(value) !== -1)
    return count.length === 0
  }

  useEffect(() => {
    if (dataSource) {
      let data = dataSource.map(item => {
        item.details = menuProcessing("_details")
        item.delete = menuProcessing("_delete")
        return item
      })
      setList(JSON.parse(JSON.stringify(data)))
    }
  }, [menuData, dataSource])

  useEffect(() => {
    getList();
  }, [currentPage, pageSize]);

  const getList = () => {
    dispatch({
      type: 'interviewReportModel/getListDatas',
      payload: {
        currentPage,
        pageSize,
        ...searchData
      },
    });
  };

  const createQutoProps = {
    onSearch: () => {
    },
    onReset: () => {
      dispatch({ type: 'interviewReportModel/updateState', payload: { currentPage: 1, searchData: null } });
      dispatch({ type: 'interviewReportModel/getListDatas', payload: { currentPage: 1, pageSize } });
    },
  };

  const addInterviewProps = {
    detailData,
    selectIndex,
    isEdit,
    editId,
    showAdd,
    setEditId,
    setIsEdit,
    editStatus,
    onCancel: () => {
      setShowAdd(false);
      dispatch({ type: 'interviewReportModel/updateState', payload: { currentPage: 1, searchData: null } });
      dispatch({ type: 'interviewReportModel/getListDatas', payload: { currentPage: 1, pageSize } });
      setSelectIndex('');
      setDetailData(null);
      setEditStatus(null)
    },
    fileType,
    getList,
    showAdd,
    edit: menuProcessing("_edit"),
    orgChooseList
  };

  const deleteInterview = record => {
    deleteVisitInformation({ id: record.id }).then(res => {
      if (res.code === 200) {
        message.success('删除成功');
        getList();
      } else {
        message.info("删除失败！");
      }
    });
  };

  const goDetail = (record, index) => {
    setShowAdd(true);
    setIsEdit(false);
    if (record) {
      setIsEdit(true);
      setEditId(record.id);
      setEditStatus(record.approvalStatus)
    } else {
      setIsEdit(false);
      setEditId('');
    }
    getAllDictionaryValueNotPage({ dictCode: 'upload_files_type' }).then(res => {
      if (res.code == 200) {
        setFileType(res.data);
      }
    });
  };

  useEffect(() => {
    let dataClone = JSON.parse(query)
    if (dataClone && dataClone.flag) {
      setTimeout(() => {
        goDetail(dataClone)
      }, 3000)

    }
  }, [query])

  const columns = [
    {
      title: '操作', key: 'operate', width: 100,
      render: (text, record, index) => {
        return (
          <div>
            <Button type="link" onClick={() => goDetail(record, index)} size="small" disabled={record.details} >  查看 </Button>
            {
              !record.deletes && (record.approvalStatus == 'new' || record.approvalStatus == 'denied') ? (<Popconfirm
                title="确定删除当前记录？"
                onConfirm={() => deleteInterview(record)}
                style={{ color: '#36bccb' }}
              >
                <Button type="link" size="small"> 删除 </Button>
              </Popconfirm>) : (<Button type="link" size="small" disabled> 删除 </Button>)
            }
          </div>
        );
      },
    },
    { title: '归属机构', dataIndex: 'affiliatedInstitutionName', key: 'affiliatedInstitutionName', ellipsis: true, },
    { title: '交易方名称', dataIndex: 'counterpartyName', key: 'counterpartyName', ellipsis: true, },
    { title: '主数据编码', dataIndex: 'masterDataCode', key: 'masterDataCode', ellipsis: true, },
    { title: '邓白氏编码', dataIndex: 'dunsCode', key: 'dunsCode', ellipsis: true, },
    { title: '业务员', dataIndex: 'createName', key: 'createName' },
    { title: '拜访时间', dataIndex: 'visitTime', key: 'visitTime', width: 100, },
    { title: '状态', dataIndex: 'approvalStatusName', key: 'approvalStatusName', },
    { title: '拜访地址', dataIndex: 'visitAddress', key: 'visitAddress', ellipsis: true, },
  ];

  const tablePaginationProps = {
    total,
    currentPage,
    pageSize,
    onPageChange: (page, size) => {
      dispatch({
        type: 'interviewReportModel/updateState',
        payload: { loading: true, currentPage: page, pageSize: size },
      });
    },
    onShowSizeChange: (page, size) => {
      dispatch({
        type: 'interviewReportModel/updateState',
        payload: { loading: true, currentPage: page, pageSize: size },
      });
    },
  };

  const onExport = () => {
    let headerNames = [];
    let fieldNames = personalizedColumn
    let lineWidths = [];
    fieldNames.forEach(item => {
      columns.forEach(i => {
        if (item === i.key) {
          headerNames.push(i.title);
          lineWidths.push(80);
        }
      });
    });
    downloadExcel({ headerNames, fieldNames, lineWidths, map: searchData ? JSON.stringify(searchData) : null, sign: 3 }, '走访报告').then(res => {
    });
  };

  const treePaginationProps = {
    personalizedColumn,
    allData,
    treeColumns,
    customKey: "interviewReport",
    onPersonalizedColumn: record => {
      dispatch({
        type: 'interviewReportModel/updateState',
        payload: { personalizedColumn: record },
      });
    },
  };

  useEffect(() => {
    let list = ['operate',];
    let data = [];
    columns.forEach(item => {
      if (list.indexOf(item.key) > -1) data.push(item);
    });
    personalizedColumn.forEach(item => {
      columns.forEach(i => {
        if (item == i.key) data.push(i);
      });
    });
    setCheckedKeys(data);
  }, [personalizedColumn, approvalList]);

  return (

    <div className={style.roomDiv}>
      {showAdd ? (
        <AddInterview {...addInterviewProps} />
      ) : (
        <Fragment>
          <Search {...createQutoProps} />
          <Card>
            <div className={styles.toolbarText}>
              <div>走访报告列表</div>
              <div style={{ display: 'flex' }}>
                <Button style={{ marginRight: 10 }} onClick={onExport} disabled={menuProcessing("_down")}>
                  导出
                </Button>
                <Button type="primary" onClick={e => goDetail()} disabled={menuProcessing("_add")}>
                  新建
                </Button>
                <TreePagination {...treePaginationProps} />
              </div>
            </div>
            <Table
              locale={{ emptyText }}
              tableLayout="fixed"
              columns={checkedKeys}
              dataSource={list}
              pagination={false}
              loading={
                loading
                  ? {
                    indicator: (
                      <div>
                        <img src={img}></img>
                      </div>
                    ),
                  }
                  : false
              }
              rowKey={record => record.id}
              scroll={{ x: 1200 }}
              size="small"
            />
            <TablePagination {...tablePaginationProps} />
          </Card>
        </Fragment>
      )}
    </div>

  );
};

const mapStateToProps = ({ interviewReportModel, globalModel }) => {
  return { interviewReportModel, globalModel };
};

export default connect(mapStateToProps)(Index);
